package com.jokins.admin.vue.hefeng.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.hefeng.City;
import com.jokins.common.util.BusinessCode;
import com.jokins.common.util.SqlTypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 *获取城市数据
 */
@Slf4j
public class FetchCityDataFromExternal {
    final static String apiKey = "aa1950307bdf4ba187ca8136bf0f5de4";


    public static List<City> API(String cityName) {
        try {
            // 对 cityName 进行 URL 编码
            String encodedCityName = URLEncoder.encode(cityName, StandardCharsets.UTF_8);
            String url = "https://geoapi.qweather.com/v2/city/lookup?location=" + encodedCityName + "&key=" + apiKey;
            log.info("Sending request to: {}", url);

            List<City> cityList = new ArrayList<>();
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet request = new HttpGet(url);
                try (CloseableHttpResponse response = httpClient.execute(request)) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    log.info("Received response with status code: {}", statusCode);
                    if (statusCode != 200) {
                        log.error("Request failed with status code: {}", statusCode);
                        throw new BusinessException("Request to external API failed with status code: ",BusinessCode.SERVER_ERROR);
                    }

                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String responseBody = EntityUtils.toString(entity);
                        JSONObject jsonObject = JSONObject.parseObject(responseBody);
                        String code = jsonObject.getString("code");
                        if (!"200".equals(code)) {
                            log.error("External API returned error code: {}", code);
                            throw new BusinessException("External API returned error code: " ,BusinessCode.SERVER_ERROR);
                        }

                        JSONArray locationArray = jsonObject.getJSONArray("location");
                        for (int i = 0; i < locationArray.size(); i++) {
                            JSONObject location = locationArray.getJSONObject(i);
                            City city = new City();
                            SqlTypeConverter.copyEntity(location, city);
                            city.setCityId(location.getString("id"));
                            city.setName(location.getString("name"));
                            city.setLat(location.getString("lat"));
                            city.setLon(location.getString("lon"));
                            city.setAdm2(location.getString("adm2"));
                            city.setAdm1(location.getString("adm1"));
                            city.setCountry(location.getString("country"));
                            city.setTz(location.getString("tz"));
                            city.setUtcOffSet(location.getString("utcOffset"));
                            city.setFxLink(location.getString("fxLink"));
                            city.setReferSources(JSON.toJSONString(location));
                            city.setLocationType(location.getString("type"));
                            city.setRank(location.getInteger("rank"));
                            city.setIsDst(location.getString("isDst"));
                            city.setAbbreviation(CityAbbreviationUtil.getCityPinyinAndAbbreviation(location.getString("name")));
                            cityList.add(city);
                        }
                    }
                }
            }
            return cityList;
        } catch (IOException e) {
            log.error("Failed to fetch city data from external API", e);
            throw new BusinessException("Failed to fetch city data from external API", e);
        }
    }
}
